package com.zhumo.sz.mock;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    private static final int THREAD_COUNT = 4;
    private static final int DATA_PER_THREAD = 100;

    public static void main(String[] args) {
        // 创建线程安全的集合
        List<String> synchronizedDataCollection = Collections.synchronizedList(new ArrayList<>());

        // 创建一个固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);

        // 提交任务到线程池
        for (int i = 0; i < THREAD_COUNT; i++) {
            executor.submit(() -> {
                for (int j = 0; j < DATA_PER_THREAD; j++) {
                    // 创建数据条目
                    String data = Thread.currentThread().getName() + ": Data " + j;
                    synchronizedDataCollection.add(data);
                }
            });
        }

        // 关闭线程池并等待所有任务完成
        executor.shutdown();
        while (!executor.isTerminated()) {
            // 等待所有任务执行完成
        }

        // 所有任务执行完毕后，打印集合大小和内容
        System.out.println("Data collection size: " + synchronizedDataCollection.size());
        synchronizedDataCollection.forEach(System.out::println);
    }
}